package com.ruoyi.common.redis;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.DefaultBaseTypeLimitingValidator;
import com.ruoyi.common.base.BaseMap;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.redis.listener.NbcioRedisListener;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Component;

/**
 *  接受消息并调用业务逻辑处理器
 *  @author nbacheng
 *  @date 2023-09-20
 */
@Component
@Data
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class RedisReceiver {

    private final ObjectMapper objectMapper;


    public void onMessage(String message) throws JsonProcessingException {

        Jackson2JsonRedisSerializer seria = new Jackson2JsonRedisSerializer<>(String.class);
        ObjectMapper copy = SpringUtil.getBean(ObjectMapper.class).copy();
        copy.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        copy.activateDefaultTyping(new DefaultBaseTypeLimitingValidator(),
            ObjectMapper.DefaultTyping.NON_FINAL);
        seria.setObjectMapper(copy);
        String deserialize = (String) seria.deserialize(message.getBytes());
        BaseMap baseMap = objectMapper.readValue(deserialize, BaseMap.class);

        Object handlerName = baseMap.get(Constants.HANDLER_NAME);
        NbcioRedisListener messageListener = SpringUtil.getBean(handlerName.toString(), NbcioRedisListener.class);
        if (ObjectUtil.isNotEmpty(messageListener)) {
            messageListener.onMessage(baseMap);
        }

        System.out.println(message);
    }

}
